package com.sweetguy.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/barrage/{userId}")
public class BarrageServer {

    //用于存储每个WS客户端的Session实例，ConcurrentHashMap保证线程安全，static保证实例唯一
    private static final Map<Long, Session> CLIENTS = new ConcurrentHashMap<>();

    //当WS客户端上线时触发
    @OnOpen
    public void onOpen(@PathParam("userId") Long userId, Session session) {
        //将客户唯一标识及其Session实例存入Map
        CLIENTS.put(userId, session);
        log.info("{} 号用户上线了", userId);
    }

    //当WS客户端下线时触发
    @OnClose
    public void onClose(@PathParam("userId") Long userId, Session session) {
        //从Map中移除该客户端及其Session实例
        CLIENTS.remove(userId);
        log.info("{} 号用户下线了", userId);
    }

    //当WS客户端链接WS服务端异常时触发
    @OnError
    public void onError(@PathParam("userId") Long userId, Throwable e, Session session) {
        log.error("{} 号用户连接或通信异常", userId, e);
    }

    //当WS服务端接收到弹幕消息的时候触发：对Map中的全部在线的WS客户端群发弹幕消息
    @OnMessage
    public void onMessage(@PathParam("userId") Long userId, String msg, Session session) {
        //遍历Map容器并向所有在线的客户端推送该消息
        CLIENTS.keySet().forEach(key -> CLIENTS.get(key).getAsyncRemote().sendText(msg));
        log.info("{} 号用户发来弹幕： {}", userId, msg);
    }
}
